﻿#include <iostream>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>

/*
* Note
* osg::ref_ptr实现类似下面。
* osg的所有对象都继承自osg::Referenced，这个对象有引用计数功能。
*/
class Real
{
public:
	Real()
	{
		count = 0;
		std::cout << "Real has been created" << std::endl;
	}
	~Real()
	{
		std::cout << "Real has been destroyed" << std::endl;
	}

	void ref()
	{
		count++;
	}

	void unref()
	{
		count--;
		if (count == 0)
		{
			delete this;
		}
	}

private:
	int count;

};

template <class T>
class ref_pter
{
public:
	ref_pter()
	{
		_ptr = nullptr;
	}

	ref_pter(T* ptr)
	{
		_ptr = ptr;
		if (_ptr)
		{
			_ptr->ref();
		}
	}

	~ref_pter()
	{
		if (_ptr)
		{
			_ptr->unref();
		}
	}

	ref_pter& operator=(T* ptr)
	{
		T* temp = _ptr;
		_ptr = ptr;
		if (_ptr)
		{
			_ptr->ref();
		}
		if (temp) // 之前的对象计数要减一，为零则释放
		{
			temp->unref();
		}
		return *this;
	}

	T* get()
	{
		return _ptr;
	}

	operator T* () const // 重载()操作
	{
		return _ptr;
	}

	T* operator ->() const	// 重载->
	{
		return _ptr;
	}

	T& operator *() const	// 重载*
	{
		return *_ptr;
	}

private:
	T* _ptr;
};

void foo(Real *s)
{

}

int main()
{
	//ref_pter<Real> rp = new Real;
	//foo(rp);
	//std::cout << "main is running" << std::endl;

	ref_pter<osgViewer::Viewer> viewer = new osgViewer::Viewer;
	viewer->setSceneData(osgDB::readNodeFile("cow.osg"));
	viewer->setUpViewInWindow(100, 100, 800, 600);
	return viewer->run();
}